import flask
import import_ipynb
import mysql.connector
from functions import create_connection, close_connection, check_tables, search_and_display_self, register, login
from functions import search_and_display_self, update_table, fetch_table_data, update_user_info

app = flask.Flask(__name__)
sql=create_connection()

## 根跳转登录
@app.route('/')
def home():
    return flask.redirect(flask.url_for('route_login'))


## 登录页面
@app.route('/route_login', methods=['GET', 'POST'])
def route_login():
    if flask.request.method == 'POST':
        username = flask.request.form.get('username')
        print(username)
        password = flask.request.form.get('password')
        result = login(sql, username, password)
        if result:
            return f'Successfully logged in as {username}'
        else:
            return f'Invalid username or password.'
    return flask.render_template('./login.html')


## 注册页面
@app.route('/route_register', methods=['GET', 'POST'])
def route_register():
    if flask.request.method == 'POST':
        username = flask.request.form.get('username')
        password = flask.request.form.get('password')
        realname = flask.request.form.get('realname')
        # 这里可以添加注册逻辑
        result = register(sql, username, password, realname)
        print(result)
        if result == 1:
            return f'Successfully registered user {username}.'
        elif result == 2:
            return f'Username already exists.'
        else:
            return f'Failed to register user.'
    return flask.render_template('register.html')
    
## 管理员界面
@app.route('/route_admin_display_users', methods=['GET', 'POST'])
def route_admin_display_users():

    
    if flask.request.method == 'POST':
        action = flask.request.form.get('action')

        ## 修改用户信息
        if action == 'update_user':
            user_id = flask.request.form.get('user_id')
            column_name = flask.request.form.get('column_name')
            new_value = flask.request.form.get('new_value')
            update_user_info(sql, user_id, column_name, new_value)

            print('User info change successfully')
            return flask.redirect(flask.url_for('route_admin_display_users'))
        ## 添加删除列
        elif action == 'update_table':
            table_names = flask.request.form['table_name']
            operation = flask.request.form['operation']
            column = flask.request.form['column']
            type = flask.request.form['type']
            update_table(sql, table_names, operation, column, type)
            return flask.redirect(flask.url_for('route_admin_display_users'))

    #显示用户信息所需的数据
    cursor = sql.cursor()
    cursor.execute("SHOW TABLES")
    table_names = [table[0] for table in cursor.fetchall()]
    column_names, rows = fetch_table_data(sql, "users")
    return flask.render_template('admin_display_users.html', table_name=table_names, columns=column_names, users_data=rows)



app.run(debug=True,use_reloader=False)
